import { useState } from 'react';

const ChatComponent = () => {
  const [content, setContent] = useState('你好写一篇100字的短文');
  const [messages, setMessages] = useState('');

  const submit = async () => {
    setMessages('')
    try {
      const response = await fetch("http://localhost:3000/api/chat/messages", {
        headers: {
          "Content-Type": "application/json",
        },
        method: "POST",
        body: JSON.stringify({
          message: content
        }),
      });
      const data = response.body;
      if (!data) {
        return;
      }
      const reader = data.getReader();
      const decoder = new TextDecoder("utf-8");
      let done = false;
      while (!done) {
        const { value, done: doneReadingStream } = await reader.read();
        done = doneReadingStream;
        const chunkValue = decoder.decode(value);
        setMessages((v) => v + chunkValue)
        await new Promise((resolve) => setTimeout(resolve, 100));
      }
    } catch (error) {
      console.log(error)
    }
  }

  return (
    <div>
      <h1>Chat</h1>
      <div>
        {messages}
      </div>
      <input value={content} onChange={(e) => setContent(e.target.value)} />
      <button onClick={() => submit()} >提交</button>
    </div>
  );
};

export default ChatComponent;
